<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索和添加用户 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList"
            @keyup.enter.native="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户数据表格 -->
      <el-table :data="userList" style="width: 100%" stripe border>
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="username" label="姓名">
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
        </el-table-column>
        <el-table-column prop="mobile" label="电话">
        </el-table-column>
        <el-table-column prop="role_name" label="角色">
        </el-table-column>
        <el-table-column label="状态" width="70px">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="修改" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserInfo(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[5, 10, 25, 50]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @closed="clearFrom">
        <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="80px"
          class="demo-ruleForm">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input type="password" v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="requestAddUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息对话框 -->
      <el-dialog title="修改用户" :visible.sync="editUserdialogVisible" width="50%" @closed="clearEditFrom">
        <el-form :model="editUserForm" :rules="editUserFormRules" ref="editUserFormRef" label-width="80px">
          <el-form-item label="用户名称">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="requestEditUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="checkedRole = ''">
        <div>
          <p>当前的用户：{{ setRoleuserInfo.username }}</p>
          <p>当前的角色：{{ setRoleuserInfo.role_name }}</p>
          <p>分配新角色：
            <el-select v-model="checkedRole" placeholder="请选择">
              <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="sendSetRoleRequest">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  created () {
    this.getUserList()
  },
  data () {
    // 自定义验证规则
    var checkEmail = (rule, value, callback) => {
      var regEmail = /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}$/
      if (!regEmail.test(value)) return callback(new Error('邮箱格式不正确'))
      callback()
    }
    var checkMobile = (rule, value, callback) => {
      var regMobile = /^0?(13|14|15|17|18)[0-9]{9}$/
      if (!regMobile.test(value)) return callback(new Error('手机号码格式不正确'))
      callback()
    }
    return {
      // 查询用户信息
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      // 添加用户对话框显示与隐藏
      addDialogVisible: false,
      // 添加用户表单信息
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''

      },
      // 添加用户信息验证规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户信息对话框显示与隐藏
      editUserdialogVisible: false,
      // 修改用户表单信息
      editUserForm: {},
      // 修改用户信息验证规则
      editUserFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 分配角色对话框开启和关闭
      setRoleDialogVisible: false,
      // 当前分配角色的用户信息
      setRoleuserInfo: {},
      // 获取的角色列表
      rolesList: [],
      // 选中的角色
      checkedRole: ''
    }
  },
  methods: {
    // 获取用户列表信息
    async getUserList () {
      let { data: res } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听一页显示多少条数据按钮
    handleSizeChange (size) {
      this.queryInfo.pagesize = size
      this.getUserList()
    },
    // 监听换页按钮
    handleCurrentChange (size) {
      this.queryInfo.pagenum = size
      this.getUserList()
    },
    // 监听用户状态按钮的改变
    async userStateChange (userInfo) {
      // console.log(userInfo)
      let { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 关闭用户添加对话框清空表单内容
    clearFrom () {
      this.$refs.addUserFormRef.resetFields()
    },
    // 发送添加用户请求
    requestAddUser () {
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$http.post('users', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.addDialogVisible = false
        this.$message.success(res.meta.msg)
        this.getUserList()
      })
    },
    // 修改用户按钮点击事件
    async editUserInfo (userInfo) {
      let { data: res } = await this.$http.get('users/' + userInfo.id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editUserdialogVisible = true
      this.editUserForm = res.data
    },
    // 关闭用户修改对话框清空表单内容
    clearEditFrom () {
      this.$refs.editUserFormRef.resetFields()
    },
    // 发送修改用户请求
    requestEditUser () {
      this.$refs.editUserFormRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await this.$http.put('users/' + this.editUserForm.id, { email: this.editUserForm.email, mobile: this.editUserForm.mobile })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.editUserdialogVisible = false
        this.$message.success(res.meta.msg)
        this.getUserList()
      })
    },
    // 删除用户
    async deleteUser (id) {
      let confirm = await this.$messageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirm !== 'confirm') return this.$message('已取消删除')
      let { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getUserList()
    },
    // 分配角色按钮点击事件
    async setRole (userInfo) {
      this.setRoleuserInfo = userInfo
      let { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 提交分配角色信息
    async sendSetRoleRequest () {
      if (!this.checkedRole) return this.$message.error('请选择角色')
      let { data: res } = await this.$http.put(`users/${this.setRoleuserInfo.id}/role`, { rid: this.checkedRole })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.setRoleDialogVisible = false
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
